import { parseTime } from './common'

/**
 * @param {String} fmt
 * @returns {String}
 * @example new Date().Format('yyyy-MM-dd hh:mm')
 */
/* eslint-disable no-extend-native */
Date.prototype.Format = function (fmt) {
  const o = {
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3),
    S: this.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (const k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr((o[k] + '').length))
  return fmt
}

// global date format
export function dateFmt(val, fmt = 'yyyy-MM-dd') {
  if (!val) return ''
  return new Date(val).Format(fmt)
}

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (!cellValue || cellValue === '') return ''
  var date = new Date(cellValue)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = !url ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} fn
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export const debounce = (fn, wait = 500, immediate = false) => {
  let timer
  return (...args) => {
    timer && clearTimeout(timer)
    immediate && !timer && fn.apply(this, args)
    timer = setTimeout(() => {
      timer = null
      !immediate && fn.apply(this, args)
    }, wait)
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

/**
 * Change the flat list to a tree
 * @param {Array} list
 * @param {Object} [opts]
 * @param {string} [opts.id='id']
 * @param {string} [opts.parent='parentId']
 * @param {string} [opts.children='children']
 * @returns {Array}
 */
export function flatList2tree(list, opts = {}) {
  const { id = 'id', parent = 'parentId', children = 'children' } = opts
  const tree = []
  const record = {}
  const ids = list.reduce((o, i) => !void (i[id] && (o[i[id]] = 1)) && o, {})
  list.map(i => {
    const uid = i[id]
    const pid = i[parent]
    if (!uid) return
    i[children] = record[uid] || (record[uid] = [])
    if (!pid) return tree.push(i)
    !record[pid] && (record[pid] = [])
    record[pid].push(i)
    // parentId 非空的根结点
    if (!ids[pid]) tree.push(i)
  })
  return tree
}

/**
 * Get path from tree by key
 * @param {Array} list
 * @param {string|number} val
 * @param {Object} [opts]
 * @param {string} [opts.id='id']
 * @param {string} [opts.children='children']
 * @param {string|null} [opts.value='id']
 * @returns {Array}
 */
export function getPathFromTree(list, val, opts = {}) {
  const { id = 'id', children = 'children', value = 'id' } = opts
  const arr = []
  function fn(list) {
    if (!list?.length) return
    for (const i of list) {
      arr.push(value ? i[value] : i)
      if (i[id] === val) return true
      if (fn(i[children])) return true
      arr.pop()
    }
  }
  fn(list)
  return arr
}

export function getFirstLeaf(list) {
  let res = {}
  function fn(val) {
    if (!val) return
    for (const i of val) {
      if (res.isLeaf) return
      if (i.isLeaf) return (res = i)
      fn(i.children)
    }
  }
  fn(list)
  return res
}

/**
 * Remove empty array
 * @param {Array} list
 * @param {string} [field='children']
 * @returns {Array}
 */
export function removeEmptyArray(list, field = 'children') {
  list.map(i => {
    if (!i[field] || !Array.isArray(i[field])) return
    if (!i[field].length) return delete i[field]
    removeEmptyArray(i[field], field)
  })
  return list
}

/**
 * 过滤无叶子的空枝
 * @param {Array} list
 * @returns {Array}
 */
export function removeEmptyBranch(list) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (item.isLeaf) continue
    if (item.children?.length) item.children = removeEmptyBranch(item.children)
    if (item.children?.length) continue
    delete list[i]
  }
  return list.filter(i => i)
}

/**
 * 判断是否对象
 * @param {Object} obj
 * @returns {Boolean}
 */
export const isObject = obj => Object.prototype.toString.call(obj) === '[object Object]'

/**
 * 对象字段排序，返回新对象
 * @param {Object} obj
 * @returns {Object}
 */
export const sortObjectKeys = obj =>
  Object.keys(obj)
    .sort()
    .reduce((o, k) => {
      const val = obj[k]
      o[k] = isObject(val) ? sortObjectKeys(val) : val
      return o
    }, {})

/**
 * 判断两个对象相等
 * @param {Object} a
 * @param {Object} b
 * @returns {Boolean}
 */
export const isObjectValueEqual = (a, b) => JSON.stringify(sortObjectKeys(a)) === JSON.stringify(sortObjectKeys(b))

/**
 * 判断对象内字段是否有相似或相等于指定值
 * @param {Object} data
 * @param {Object} opts
 * @param {Object} opts.like 指定相似值 { [k in String]: String }
 * @param {Object} opts.eq 指定相等值 { [k in String]: String | Number | Boolean | null }
 * @returns {Boolean}
 * @example isLikeOrEqual({ name: 'Hello', addr: 'world', age: 18 }, { like: { name: 'he', addr: 'wo' }, eq: { age: 18 } }) // true
 * 注：值为空字符串，则该字段为真
 */
export const isLikeOrEqual = (data, opts) => {
  if (!isObject(data)) return false
  const arr = []
  if (opts.like) {
    Object.keys(opts.like).map(k => {
      const val1 = (data[k] || '').toLowerCase()
      const val2 = (opts.like[k] || '').toLowerCase()
      arr.push(val2 ? val1.includes(val2) : true)
    })
  }
  if (opts.eq) {
    Object.keys(opts.eq).map(k => {
      const val1 = data[k]
      const val2 = opts.eq[k]
      // 空字符串则为真
      const isEqual = typeof val2 === 'string' && !val2 ? true : val1 === val2
      arr.push(isEqual)
    })
  }
  // 每项为真则为真
  return arr.filter(i => i).length === arr.length
}

/**
 * 横线转驼峰命名
 * @param {String} str
 * @returns {String}
 * @example camelize('ab-cd-ef') // abCdEf
 */
export const camelize = str => str.replace(/-(\w)/g, (match, c) => (c ? c.toUpperCase() : ''))

// 常用图片扩展名
export const pictureExtNames = ['jpg', 'jpeg', 'png', 'bmp', 'gif', 'webp', 'ico', 'avif', 'svg', 'tif']
